"""
@Time: 2021/1/13 下午 8:25
@Author: jinzhuan
@File: bert_softmax.py
@Desc: 
"""
import sys
sys.path.append('/data/zhuoran/code/cognlp')
sys.path.append('/data/zhuoran/cognlp')

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import RandomSampler
from cognlp import *


torch.cuda.set_device(2)
device = torch.device('cuda')

from cognlp.io.processor.et.cluener import ClueNERProcessor
from cognlp.io.loader.et.cluener import ClueNERLoader

loader = ClueNERLoader()
train_data, dev_data = loader.load_all('../../../cognlp/data/et/cluener/data')
processor = ClueNERProcessor(path='../../../cognlp/data/et/cluener/data/')
vocabulary = Vocabulary.load('../../../cognlp/data/et/cluener/data/vocabulary.txt')

train_datable = processor.process(train_data)
train_dataset = DataTableSet(train_datable)
train_sampler = RandomSampler(train_dataset)

dev_datable = processor.process(dev_data)
dev_dataset = DataTableSet(dev_datable)
dev_sampler = RandomSampler(dev_dataset)

model = BertSoftmax(vocabulary, bert_model='hfl/chinese-roberta-wwm-ext')
metric = SpanFPreRecMetric(vocabulary)
loss = nn.CrossEntropyLoss(ignore_index=0)
optimizer = optim.Adam(model.parameters(), lr=0.00005)

trainer = Trainer(model,
                  train_dataset,
                  dev_data=dev_dataset,
                  n_epochs=20,
                  batch_size=25,
                  loss=loss,
                  optimizer=optimizer,
                  scheduler=None,
                  metrics=metric,
                  train_sampler=train_sampler,
                  dev_sampler=dev_sampler,
                  drop_last=False,
                  gradient_accumulation_steps=1,
                  num_workers=5,
                  save_path="../../../cognlp/data/et/cluener/model",
                  save_file=None,
                  print_every=None,
                  scheduler_steps=None,
                  validate_steps=None,
                  save_steps=None,
                  grad_norm=None,
                  use_tqdm=True,
                  device=device,
                  device_ids=[2],
                  callbacks=None,
                  metric_key=None,
                  writer_path='../../../cognlp/data/et/cluener/tensorboard',
                  fp16=False,
                  fp16_opt_level='O1',
                  checkpoint_path=None,
                  task='cluener',
                  logger_path='../../../cognlp/data/et/cluener/logger')

trainer.train()